class GameController < ApplicationController

  def list
    resp = '['
    Table.all.each { |table|
      resp<<table.to_list_json<<','
    }
    resp = resp.chop<<']' if resp.last.eql?(',')
    respond_to do |format|
      response.headers["Content-Type"] = "application/json"
      format.json {render :json => resp}
    end
  end

  def game
    if params[:partial]
      render :partial => "partial_list"
    end
  end

  def user_money
    respond_to do |format|
      response.headers["Content-Type"] = "application/json"
      format.json {render :json => '{"money":'+User.find(cookies[:current_user_id]).money.to_s+'}'}
    end
  end

  def player_money
    respond_to do |format|
      response.headers["Content-Type"] = "application/json"
      format.json {render :json => '{"money":'+Player.find_all_by_user_id__and_table_id(cookies[:current_user_id],params[:id]).money.to_s+'}'}
    end
  end

  def sit
    table = Table.find(params[:id])
    respond_to do |format|
      response.headers["Content-Type"] = "application/json"
      unless table.nil?
        table.player<<Player.new(:user_id => cookies[:current_user_id],
                                                     :money => params[:game_player_bank])
        user = User.find(cookies[:current_user_id])
        user.money -= Integer(params[:game_player_bank])
        user.save
        format.json {render :json => '{ "state":true }'}
      else
        format.json {render :json => '{ "state":false }'}
      end
    end
  end
  
  def stand
    table = Table.find(params[:id])
    respond_to do |format|
      response.headers["Content-Type"] = "application/json"
      unless table.nil?
        player = table.player.find_by_user_id(cookies[:current_user_id])
        unless player.nil?
          player.user.money += player.money
          player.user.save
          player.delete
          format.json {render :json => '{ "state":true }'}
        else
          format.json {render :json => '{ "state":false }'}
        end
      else
        format.json {render :json => '{ "state":false }'}
      end
    end
  end

  def update
    respond_to do |format|
      response.headers["Content-Type"] = "application/json"
      format.json {render :json => Table.find(params[:id]).to_stage_json}
    end
  end
end
